package cn.xiongxf.user.service.impl;

import cn.xiongxf.basic.constant.VerifyCodeConstant;
import cn.xiongxf.basic.exception.BusinessException;
import cn.xiongxf.basic.util.Md5Utils;
import cn.xiongxf.basic.util.StrUtils;
import cn.xiongxf.user.domain.Logininfo;
import cn.xiongxf.user.domain.User;
import cn.xiongxf.user.domain.UserDto;
import cn.xiongxf.user.mapper.LogininfoMapper;
import cn.xiongxf.user.mapper.UserMapper;
import cn.xiongxf.user.service.IUserService;
import cn.xiongxf.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void emailRegister(UserDto userDto) throws MessagingException {
        String email = userDto.getEmail();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        // 1.校验
        // 1.1.校验空值
        if (StringUtils.isEmpty(email)
        || StringUtils.isEmpty(password)
        || StringUtils.isEmpty(password) ){
            throw new BusinessException("数据不能为空！");
        }
        // 1.2.校验邮箱是否被注册 - 查询t_user表
        User user = userMapper.loadByEmail(email);
        if (user != null){
            throw new BusinessException("该邮箱已注册！");
        }
        // 1.3.校验两次密码是否一致
        if (!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致！");
        }

        // 2.保存数据
        User user2 = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user2);
        // 先保存t_logininfo对象（获取自增id，设置到t_user）
        logininfoMapper.save(logininfo);
        // 再保存t_user对象
        user2.setLogininfoId(logininfo.getId());
        userMapper.save(user2);

        // 3.发送邮件：点击邮件完成注册
        MimeMessage mimeMessageessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessageessage, true, "UTF-8");
        // 发件人
        helper.setFrom("1229234469@qq.com");
        // 收件人
        helper.setTo(email);
        // 主题
        helper.setSubject("用户账号激活邮件");
        // 正文
        helper.setText("<h1>账号注册成功</h1><br>" +
                "<a href='http://localhost:8080/user/register/email/active/"+user2.getId()+"'>点击链接激活</a>",true);
        // 发送
        javaMailSender.send(mimeMessageessage);

    }

    @Override
    public void activeEmailRegister(Long id) {
        User user = userMapper.loadById(id);
        user.setState(1);
        userMapper.update(user);
    }

    @Override
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();

        // 1.校验
        // 1.1.校验空值
        if (StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(phoneCode)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("数据不能为空！");
        }

        // 1.2.校验两次密码是否一致
        if (!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致！");
        }
        // 1.3.校验手机验证码：是否过期，是否正确
        // redis存值格式：key[register:18516501320] : value[123456:28608146200]
        Object phoneCodeObj = redisTemplate.opsForValue().get(VerifyCodeConstant.REGISTER_CODE_PREFIX + phone);
        if (phoneCodeObj == null){
            throw new BusinessException("手机验证码已过期！");
        }else {
            if (!phoneCode.equals(phoneCodeObj.toString().split(":")[0])){
                throw new BusinessException("手机验证码错误！");
            }
        }

        // 2.保存数据
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        // 先保存t_logininfo对象（获取自增id，设置到t_user）
        logininfoMapper.save(logininfo);
        // 再保存t_user对象
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    // UserDto转User的自定义方法
    private User userDto2User(UserDto userDto){
        User user = new User();
        // 设置用户名：email/phone
        String email = userDto.getEmail();
        String phone = userDto.getPhone();
        if (email != null){
            user.setUsername(email);
            user.setState(0);
        }
        if (phone != null){
            user.setUsername(userDto.getPhone());
            user.setState(1);
        }
        user.setPhone(userDto.getPhone());
        user.setEmail(userDto.getEmail());
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        // 加密加盐后的密码
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Logininfo user2Logininfo(User user){
        Logininfo logininfo = new Logininfo();
        // 属性同名原则拷贝对象
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return  logininfo;
    }

    @Transactional
    @Override
    public void add(User user) {
        // 获取并设置盐值、密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        // 保存t_logininfo
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);

        // 保存t_user
        user.setLogininfoId(logininfo.getId());
        super.add(user);
    }

    @Transactional
    @Override
    public void update(User user) {
        // 获取并设置盐值、密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        // 登录信息id和员工id不能修改
        super.update(user);

        // 修改t_logininfo
        User oldUser = userMapper.loadById(user.getId());
        Logininfo oldLogininfo = logininfoMapper.loadById(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,logininfoMapper);
        logininfoMapper.update(oldLogininfo);
    }

    @Transactional
    @Override
    public void del(Long id) {
        // 获取user
        User user = userMapper.loadById(id);
        // 删除logininfo
        logininfoMapper.remove(user.getLogininfoId());
        // 删除user
        super.del(id);
    }
}
